const { verifyToken } = require('../utils/jwt')
const Response = require('../utils/response')

// 管理员权限验证中间件
const adminAuthMiddleware = (req, res, next) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers.authorization
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return Response.unauthorized(res, '未提供认证令牌')
    }

    const token = authHeader.split(' ')[1]
    
    // 验证token
    const decoded = verifyToken(token)
    
    if (!decoded) {
      return Response.unauthorized(res, 'Token无效或已过期')
    }

    // 检查是否为管理员
    if (decoded.role !== 'admin') {
      return Response.forbidden(res, '无权限访问，需要管理员权限')
    }

    // 将用户信息附加到请求对象
    req.userId = decoded.userId
    req.username = decoded.username
    req.role = decoded.role
    
    next()
  } catch (error) {
    return Response.unauthorized(res, '认证失败')
  }
}

module.exports = adminAuthMiddleware











